import os
import requests
import time
import re
from datetime import datetime
from notify import send

# 环境变量为ksjsb_dat    格式为coookie&签到sig3&宝箱sig3
# 从环境变量获取参数
##cron: 15 7-23/1 * * *
##new Env("快手极速版自用")
ksjsb_data = os.getenv("ksjsb_data")
if not ksjsb_data:
    print("⚠️ 请设置环境变量 ksjsb_data")
    exit(1)
    
# 分割环境变量参数
params = ksjsb_data.split("&")
if len(params) != 3:  # 修改为3个参数
    print("❌ 环境变量格式错误，应为：cookie&sign_ns_sig3&box_ns_sig3")
    exit(1)
    
cookie_str, sign_ns_sig3, box_ns_sig3 = params[:3]  # 只取前3个参数
# 转换Cookie字符串为字典
cookies = {}
for item in cookie_str.split(";"):
    key_value = item.split("=", 1)
    if len(key_value) == 2:
        key, value = key_value
        cookies[key.strip()] = value.strip()
# 公共请求头
common_headers = {
    "Host": "nebula.kuaishou.com",
    "Connection": "keep-alive",
    "User-Agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/90.0.4430.226 KsWebView/1.8.90.671 (rel) Mobile Safari/537.36 Yoda/3.1.7-alpha26 ksNebula/12.0.40.7282 OS_PRO_BIT/64 MAX_PHY_MEM/15207 AZPREFIX/az2 ICFO/0 StatusHT/40 TitleHT/241 NetType/WIFI ISLP/0 ISDM/0 ISLB/0 locale/zh-cn DPS/17.148 DPP/95 CT/0 ISLM/0",
    "X-Requested-Width": "com.kuaishou.nebula",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Dest": "empty",
    "Referer": "https://nebula.kuaishou.com/nebula/task/earning?layoutType=4&hyId=nebula_earning_ug_cdn&source=bottom_guide_first",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
}
# 存储结果
results = []

# 1. 执行签到
sign_url = f"https://nebula.kuaishou.com/rest/wd/encourage/unionTask/signIn/report?__NS_sig3={sign_ns_sig3}&sigCatVer=1"
sign_headers = {**common_headers, "content-type": "application/x-www-form-urlencoded;charset=UTF-8"}
try:
    sign_res = requests.get(sign_url, headers=sign_headers, cookies=cookies)
    sign_data = sign_res.json()
    
    if sign_data.get("result") == 1:
        # 从响应数据结构中提取奖励信息
        report_reward = sign_data.get("data", {}).get("reportRewardResult", {})
        award_info = report_reward.get("awardInpushInfo", {})
        
        # 提取标题和金币数量
        title = award_info.get("title", "签到成功")
        suffix = award_info.get("multiDayRewardSubTitleSuffix", "")
        coin_match = re.search(r'(\d+)', suffix)
        coin_count = coin_match.group(1) if coin_match else "0"
        
        # 从eventTrackingAwardInfo中获取精确的金币数量（优先级更高）
        event_award = report_reward.get("eventTrackingAwardInfo", {}).get("awardInfo", [{}])[0]
        if event_award.get("awardType") == 1:  # 1表示金币奖励
            precise_coin = str(event_award.get("amount", coin_count))
            coin_count = precise_coin if precise_coin != "0" else coin_count
        
        # 构建详情信息
        prefix = award_info.get("multiDayRewardSubTitlePrefix", "签到奖励")
        details = f"{prefix} {suffix}" if prefix else suffix
        
        # 格式化结果
        if details.strip():
            results.append(f"🎯 {title}: +{coin_count}金币 ({details})")
        else:
            results.append(f"🎯 {title}: +{coin_count}金币")
            
    else:
        error_msg = sign_data.get("error_msg", "未知错误")
        results.append(f"⚠️ 签到: {error_msg}")
        
except Exception as e:
    results.append(f"❌ 签到请求异常: {str(e)}")
    
# 添加5秒延迟
time.sleep(5)
print("⏳ 签到完成，等待5秒后开宝箱...")

# 2. 执行开宝箱
box_url = f"https://nebula.kuaishou.com/rest/wd/encourage/unionTask/treasureBox/report?__NS_sig3={box_ns_sig3}&sigCatVer=1"
box_headers = {**common_headers, "content-type": "application/json", "Origin": "https://nebula.kuaishou.com"}
try:
    box_res = requests.post(box_url, headers=box_headers, cookies=cookies, data="{}")
    box_data = box_res.json()
    
    # 检查响应中是否有'data'字段
    response_data = box_data.get("data", box_data)
    
    if response_data.get("type") == 1:
        # 开宝箱成功
        title_info = response_data.get("title", {})
        
        # 提取金币数量和成功提示信息
        if isinstance(title_info, dict):
            reward = title_info.get("rewardCount", "0")
            success_text = title_info.get("text", "开宝箱")
        else:
            reward = response_data.get("rewardCount", "0")
            success_text = "开宝箱"
        
        # 提取进度信息
        progress_bar = response_data.get("progressBar", {})
        progress_title = progress_bar.get("title", "")
        
        # 格式化成功信息
        if progress_title:
            results.append(f"🎁 {success_text}: +{reward}金币 | {progress_title}")
        else:
            results.append(f"🎁 {success_text}: +{reward}金币")
            
    else:
        # 开宝箱失败
        title_info = response_data.get("title", {})
        
        # 尝试获取失败提示信息
        if isinstance(title_info, dict):
            if "text" in title_info:
                reason = title_info["text"]
            elif "txex" in title_info:
                reason = title_info["txex"]
            else:
                reason = response_data.get("text", "宝箱开启失败")
        else:
            reason = response_data.get("text", "宝箱开启失败")
        
        # 添加额外的进度信息
        progress_bar = response_data.get("progressBar", {})
        if "title" in progress_bar:
            reason += f" ({progress_bar['title']})"
        
        results.append(f"⛔ 开宝箱: {reason}")
        
except Exception as e:
    results.append(f"❌ 宝箱请求异常: {str(e)}")
    
# 添加5秒延迟
time.sleep(5)
print("⏳ 宝箱操作完成，准备查询收益...")

# 3. 查询收益
profit_url = "https://nebula.kuaishou.com/rest/n/nebula/account/overview"
profit_headers = {
    **common_headers,
    "Accept": "application/json, text/plain, */*",
    "Referer": "https://nebula.kuaishou.com/nebula/task/profit?layoutType=4&tab=cash&source=moneyMain&exchange_type=AUTO"
}
try:
    profit_res = requests.get(profit_url, headers=profit_headers, cookies=cookies)
    profit_data = profit_res.json()
    
    if profit_data.get("result") == 1:
        data = profit_data.get("data", {})
        coin_balance = data.get("coinBalance", "0")
        cash_balance = data.get("cashBalance", "0.00")
        accumulative_amount = data.get("accumulativeAmount", "0.00")
        
        # 将现金余额转换为浮点数进行比较
        try:
            cash_float = float(cash_balance)
        except ValueError:
            cash_float = 0.0
        
        results.append("\n💰 收益统计:")
        results.append(f"  我的金币: {coin_balance}")
        results.append(f"  我的余额: {cash_balance}元")
        # 添加提现提示
        if cash_float >= 15:
            results.append("  ✅ 余额已达到15元，可以尝试提现！")
        results.append(f"  累计赚到: {accumulative_amount}元")
    else:
        error_msg = profit_data.get("error_msg", "未知错误")
        results.append(f"⚠️ 收益查询失败: {error_msg}")
        
except Exception as e:
    results.append(f"❌ 收益查询异常: {str(e)}")
    
# 打印并发送结果
result_msg = "\n".join(results)
print("="*50)
print("✨ 快手极速版任务执行结果:")
print(result_msg)
print("="*50)
# 发送通知
send("快手极速版任务", result_msg)